package ua.epam.muzalevskiy.traction.controllers;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.log4j.Logger;

/**
 * <code>EncodingSetterFilter</code> class encoding request content type 
 * to UTF-8 if it not installed.
 *
 * @author Muzalevskiy Vitaliy
 */
public class EncodingFilter implements Filter {

    private String encoding;

    private static Logger logger = Logger.getLogger(EncodingFilter.class);
    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 
    private FilterConfig filterConfig;
    
    /**
     * Init method for this filter 
     */
    @Override
    public void init(FilterConfig filterConfig) { 
	this.filterConfig = filterConfig;
	if (filterConfig != null) {
            logger.debug("NewFilter:Initializing filter");
	}
        encoding = filterConfig.getInitParameter("requestEncoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, 
            FilterChain next) throws IOException, ServletException {
        request.setCharacterEncoding(encoding);
        next.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}
